package ioex

import (
	"bytes"
	"io"
	"sync"
)

type SyncBuffer struct {
	end bool
	b   bytes.Buffer
	m   sync.Mutex
}

func (b *SyncBuffer) Read(p []byte) (int, error) {
	for {
		if b.end && b.b.Len() <= 0 {
			break
		}
		b.m.Lock()
		n, err := b.b.Read(p)
		b.m.Unlock()
		if n > 0 {
			return n, err
		}
	}
	return 0, io.EOF
}
func (b *SyncBuffer) Write(p []byte) (int, error) {
	b.m.Lock()
	defer b.m.Unlock()
	if p == nil {
		b.end = true
		return 0, nil
	}
	return b.b.Write(p)
}
func (b *SyncBuffer) String() string {
	b.m.Lock()
	defer b.m.Unlock()
	return b.b.String()
}
func (b *SyncBuffer) Len() int {
	b.m.Lock()
	defer b.m.Unlock()
	return b.b.Len()
}
